/**
 * token相关
 * @date: 2019-12-25

 */
import qs from 'query-string';
import Cookies from 'universal-cookie';
export var ACCESS_TOKEN = 'access_token';
export var REFRESH_TOKEN = 'refresh_token';
var cookies = new Cookies();
export function getAccessToken() {
  var privateRouter = window.location.pathname.startsWith('/private');
  var privateToken = qs.parse(window.location.search) || {};
  return privateRouter ? privateToken.access_token : cookies.get(ACCESS_TOKEN, {
    path: '/'
  });
}
export function setAccessToken(token) {
  cookies.set(ACCESS_TOKEN, token, {
    path: '/'
  });
}
export function removeAccessToken() {
  cookies.remove(ACCESS_TOKEN, {
    path: '/'
  });
}
export function getRefreshToken() {
  var privateRouter = window.location.pathname.startsWith('/private');
  var privateToken = qs.parse(window.location.search) || {};
  return privateRouter ? privateToken.refresh_token : cookies.get(REFRESH_TOKEN, {
    path: '/'
  });
}
export function setRefreshToken(token) {
  cookies.set(REFRESH_TOKEN, token, {
    path: '/'
  });
}
export function removeRefreshToken() {
  cookies.remove(REFRESH_TOKEN, {
    path: '/'
  });
}
/**
 * 抽取AccessToken
 * @param {String} hash   hash值
 */

export function extractAccessTokenFromHash(hash) {
  if (hash) {
    var ai = hash.indexOf(ACCESS_TOKEN);

    if (ai !== -1) {
      var accessTokenReg = /#?access_token=[0-9a-zA-Z-]*/g; // todo 确定 确定的 access_token 头, 现在看起来时 /#access_token

      hash.match(accessTokenReg);
      var centerReg = hash.match(accessTokenReg)[0];
      var accessToken = centerReg.split('=')[1];
      return accessToken;
    }
  }

  return null;
}
/**
 * 抽取RefreshToken
 * @param {String} hash   hash值
 */

export function extractRefreshTokenFromHash(hash) {
  if (hash) {
    var ai = hash.indexOf(REFRESH_TOKEN);

    if (ai !== -1) {
      var refreshTokenReg = /#?refresh_token=[0-9a-zA-Z-]*/g; // todo 确定 确定的 access_token 头, 现在看起来时 /#access_token

      hash.match(refreshTokenReg);
      var centerReg = hash.match(refreshTokenReg)[0];
      var refreshToken = centerReg.split('=')[1];
      return refreshToken;
    }
  }

  return null;
}